package com.wisdom.benefit.jufa.utils;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import com.google.gson.JsonObject;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.entity.VersionInfo;
import com.wisdom.benefit.jufa.main.MainActivity;
import com.wisdom.benefit.jufa.net.download.DownloadListener;
import com.wisdom.benefit.jufa.widget.DividerLinearLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.io.File;
import java.util.Collections;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Created on 2019/07/31 17:08.
 *
 * @author zhoudawei
 */
public class VersionDialogUtil {

    private BaseActivity mActivity;
    private AlertDialog mDialog;
    private View mDialogView;

    public void showVersionDialog(BaseActivity activity, JsonObject object) {
        mActivity = activity;
        String json = object.toString();
        if (TextUtils.equals("0", JsonUtil.getAsString(json, "onlineType")))
            return;
        if (!TextUtils.isDigitsOnly(JsonUtil.getAsString(json, "versionCode")))
            return;
        int versionCode = Integer.valueOf(JsonUtil.getAsString(json, "versionCode"));
        if (versionCode <= PackageUtils.getVersionCode(mActivity)) {
            if (!(mActivity instanceof MainActivity))
                Toast.makeText(mActivity, "已经是最新版本", Toast.LENGTH_SHORT).show();
            return;
        }

        if (mDialog == null) {
            mDialog = new AlertDialog.Builder(mActivity).create();
            mDialogView = View.inflate(mActivity, R.layout.dialog_new_version, null);
            mDialog.setView(mDialogView);
            mDialog.setCancelable(false);
        }

        mDialog.show();
        if (mDialog.getWindow() != null)
            mDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        String versionName = JsonUtil.getAsString(json, "versionName");
        if (!versionName.startsWith("v") && !versionName.startsWith("V")) {
            versionName = "V" + versionName;
        }
        ((TextView) mDialogView.findViewById(R.id.tv_version)).setText(versionName.toUpperCase());
        DividerLinearLayout layout = mDialogView.findViewById(R.id.layout_desc);
        List<VersionInfo> list = JsonUtil.getListFromJson(json, "contentList", VersionInfo.class);
        Collections.sort(list);
        CommonAdapter<VersionInfo> adapter = new CommonAdapter<VersionInfo>(mActivity, R.layout.item_list_new_version_desc, list) {
            @Override
            protected void convert(ViewHolder viewHolder, VersionInfo item, int position) {
                viewHolder.setText(R.id.tv_desc, item.getVersionContent());
            }
        };
        layout.setAdapter(adapter);
        mDialogView.findViewById(R.id.btn_not_update).setOnClickListener(mOnClickListener);
        mDialogView.findViewById(R.id.btn_not_update).setVisibility(View.VISIBLE);
        mDialogView.findViewById(R.id.btn_now_update).setOnClickListener(mOnClickListener);
        mDialogView.findViewById(R.id.btn_now_update).setVisibility(View.VISIBLE);
        mDialogView.findViewById(R.id.btn_now_update).setTag(JsonUtil.getAsString(json, "filePath"));
        mDialogView.findViewById(R.id.progress_bar).setVisibility(View.GONE);
        int publishStatus = JsonUtil.getAsInt(json, "publishStatus");
        if (publishStatus == 1) {
            mDialog.setCancelable(false);
            mDialogView.findViewById(R.id.btn_not_update).setVisibility(View.GONE);
        }
    }

    private View.OnClickListener mOnClickListener = v -> {
        if (v.getId() == R.id.btn_not_update) {// 暂不更新
            mDialog.dismiss();
        } else if (v.getId() == R.id.btn_now_update) {// 立即更新
            RxPermissions rxPermissions = new RxPermissions(mActivity);
            Disposable disposable = rxPermissions.requestEachCombined(
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(permission -> { // will emit 1 Permission object
                        if (permission.granted) {
                            // All permissions are granted !
                            downloadApk(String.valueOf(v.getTag()));
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // At least one denied permission without ask never again
                            Toast.makeText(mActivity, R.string.permission_request_denied, Toast.LENGTH_SHORT).show();
                        } else {
                            // At least one denied permission with ask never again
                            // Need to go to the settings
                            Toast.makeText(mActivity, R.string.permission_request_denied, Toast.LENGTH_SHORT).show();
                        }
                    });
            mActivity.addDisposable(disposable);
        }
    };

    private void downloadApk(String apkUrl) {
        ProgressBar progressBar = mDialogView.findViewById(R.id.progress_bar);
        DownloadUtil downloadUtil = new DownloadUtil();
        downloadUtil.downloadFile(apkUrl, new DownloadListener() {
            @Override
            public void onStart() {
                mActivity.runOnUiThread(() -> {
                    mDialogView.findViewById(R.id.btn_not_update).setVisibility(View.GONE);
                    mDialogView.findViewById(R.id.btn_now_update).setVisibility(View.GONE);
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(0);
                });
            }

            @Override
            public void onProgress(int progress) {
                mActivity.runOnUiThread(() -> progressBar.setProgress(progress));
            }

            @Override
            public void onFinish(String localPath) {
                File apkFile = new File(localPath);
                openAPKFile(apkFile);
                mDialog.dismiss();
            }

            @Override
            public void onFailure(String errorInfo) {
                mDialog.dismiss();
            }
        });
    }

    private void openAPKFile(File apkFile) {
        String mimeDefault = "application/vnd.android.package-archive";
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //兼容7.0
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                //这里牵涉到7.0系统中URI读取的变更
                Uri contentUri = FileProvider.getUriForFile(mActivity, "com.wisdom.benefit.jufa.fileprovider2", apkFile);
                intent.setDataAndType(contentUri, mimeDefault);
                //兼容8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean hasInstallPermission = mActivity.getPackageManager().canRequestPackageInstalls();
                    if (!hasInstallPermission) {
                        startInstallPermissionSettingActivity();
                        return;
                    }
                }
            } else {
                intent.setDataAndType(Uri.fromFile(apkFile), mimeDefault);
            }
            if (mActivity.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
                //如果APK安装界面存在，携带请求码跳转。使用forResult是为了处理用户取消安装的事件。
                //外面这层判断理论上来说可以不要，但是由于国内的定制，这个加上还是比较保险的
                mActivity.startActivityForResult(intent, 2);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //后面跟上包名，可以直接跳转到对应APP的未知来源权限设置界面。使用startActivityForResult 是为了在关闭设置界面之后，获取用户的操作结果，然后根据结果做其他处理
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + mActivity.getPackageName()));
        mActivity.startActivityForResult(intent, 1);
    }
}
